<?php

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerMami;
use app\common\customer\validate\CustomerProductValidate;
use think\db\exception\DbException;

class Product extends Api
{
    public function read()
    {
        $post = $this->request->post();

        // 获取意向产品
        $productModel = new CustomerMami();
        $products = $productModel->where('member_id', $post['id'])->select();
        foreach ($products as $row) {
            $row->append(['creator', 'tag']);
        }
        $result['products'] = $products;

        return success($result);
    }

    public function save()
    {
        $post = $this->request->post();

        $validate = new CustomerProductValidate();
        if (!$validate->scene('create')->check($post)) {
            return error([], $validate->getError());
        }

        $productModel = new CustomerMami();
        $productModel->startTrans();
        try {
            $row = $productModel->where('id', $post['id'])->find();
            $row->save($post);
            $productModel->commit();

        } catch (DbException $e) {
            $productModel->rollback();
            return error([], $e->getMessage());
        }

        if (!empty($post['customer']['fullname'])) {
            $fullname = $post['customer']['fullname'];
            Customer::update(['fullname'=>$fullname],['id'=>$post['member_id']]);
        }

        return success([], "更新成功");
    }
}